<?php
declare (strict_types = 1);

namespace app\index\controller;

use app\common\validate\Email;
use app\common\validate\Password;
use app\index\BaseController;
use app\index\model\Article;
use app\index\model\Block;
use app\index\model\User as UserModel;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Log;
use think\Request;
use app\index\model\Topic;
use app\admin\traits\UploadImage;

class User extends BaseController
{
    use UploadImage;


    //中间件
    protected $middleware = [
        'method:ajax' => ['only'=>[
            'savePassword',
            'saveEmail',
            'saveAvatar'
        ]],
        'access:@' => ['only'=>[
            'setting',

            'setPassword',
            'savePassword',

            'setEmail',
            'saveEmail',

            'setAvatar',
            'saveAvatar'
        ]],
    ];

    /**
     * 上传头像图片
     */
    public function uploadAvatar(){
        return $this->upload(UserModel::UP_FIELD,
            UserModel::UP_FOLDER,
            ['width'=>320, 'height'=>320]
            );
    }




    /**
     * 作者中心
     * @param Request $request
     * @param int $id
     * @return \think\response\View
     * @throws \think\Exception
     */
    public function read(Request $request, int $id){
        //用户模型
        $model = $this->getModel(UserModel::class, $id);

        //不是作者不显示此页面
        if (! count($model->roles)) abort(404, '页面不存在.');


        return view('read',[
            'model' => $model,
            //文章列表
            'count' => Article::getCount(['user_id'=>$model->id]),
            'topic_count' => Topic::getCount(['user_id' => $model->id]),
            'limit' => Article::LIMIT_NUM,


            'crumb' => [
                'home' => '/',
                $model->showName => $request->url()
            ],
            //*推荐作者
            'activeAuthors' => Block::getActiveAuthors(),

            //*作者话题
            'topic_list' => Topic::getTopicsByUser((int) $model->id),
        ]);
    }

    /**
     * 设置中心
     */
    public function setting(){

        return view('setting',[
            'crumb' => [
                'home' => '/',
                '设置' => $this->request->url()
            ]
        ]);
    }

    /**
     * 修改密码
     */
    public function setPassword(){
        return view('set-password',[
            'crumb' => [
                'home' => '/',
                '设置密码' => $this->request->url()
            ]
        ]);
    }

    /**
     * 保存修改的密码
     */
    public function savePassword(){
        try{
            $data = request()->only(['ori_password','new_password','re_password']);

            validate(Password::class)->check($data);

            //修改密码
            $user = app()->user->getIdentity();
            $ret = $user->save([
                'password_hash' => $user->generatePasswordHash($data['new_password'])
            ]);
            if($ret === false)
                throw new Exception('修改失败.');

            //登出
            app()->user->logout();

            return json([
                'code' => 0,
                'msg' => '修改成功.'
            ]);

        }catch (ValidateException $e){
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }catch (\Exception $e){
            //系统错误
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 修改昵称
     * @return \think\response\View
     */
    public function setNickname(){
        return view('set-nickname',[
            'crumb' => [
                'home' => '/',
                '设置昵称' => $this->request->url()
            ]
        ]);
    }

    /**
     * 保存修改的昵称
     */
    public function saveNickname(){
        try{
            $data = request()->only(['nickname']);

            validate([
                'nickname'          => 'require|max:7|unique:user,nickname',
            ],[
                'nickname.require'  => '必须填写昵称',
                'nickname.max'      => '昵称最多7个字符',
                'nickname.unique'   => '昵称已存在',
                'avatar.max'        => '头像连接错误',
                'avatar.isFile'     => '请重新选择图片.',
            ])->check($data);

            //修改密码
            $user = app()->user->getIdentity();
            $ret = $user->save([
                'nickname' => $data['nickname']
            ]);
            if($ret === false)
                throw new Exception('修改失败.');

            return json([
                'code' => 0,
                'msg' => '修改成功.'
            ]);

        }catch (ValidateException $e){
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }catch (\Exception $e){
            //系统错误
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 修改邮箱
     */
    public function setEmail(){
        return view('set-email',[
            'crumb'=>[
                'home' => '/',
                '修改邮箱' => $this->request->url()
            ]
        ]);
    }

    /**
     * 保存邮箱
     */
    public function saveEmail(){
        try{
            $data = request()->only(['email','captcha']);

            validate(Email::class)->check($data);

            //修改邮箱
            $user = app()->user->getIdentity();
            $ret = $user->save([
                'email' => $data['email']
            ]);
            if($ret === false)
                throw new Exception('修改失败.');


            return json([
                'code' => 0,
                'msg' => '修改成功.'
            ]);

        }catch (ValidateException $e){
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }catch (\Exception $e){
            //系统错误
            //Log::error($e->getMessage());
            return json([
                'code' => 1,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 修改头像
     */
    public function setAvatar(){
        return view('set-avatar',[
            'crumb' => [
                'home' => '/',
                '设置头像' => $this->request->url()
            ]
        ]);
    }
    /**
     * 保存头像
     *
     */
    public function saveAvatar(){
        try{
            $data = request()->only(['avatar']);
            validate([
                'avatar' => 'require'
            ],[
                'avatar.require' => '请选择图片.'
            ])->check($data);

            if( !app()->user->getIdentity()->save($data) )
                throw new Exception('修改失败.');
            //修改成功
            return json(['code'=>0,'msg'=>'修改成功']);

        } catch (ValidateException $e) {

            //验证错误
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        } catch (\Exception $e){

            //系统错误
            //Log::error($e->getMessage());
            return json(['code'=>1,'msg'=>$e->getMessage()]);
        }
    }
}
